<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Contracts\Validation\Validator;
use App\Utils\ApiResponse;

/**
 * WordPress文章查询请求验证类
 */
class PostQueryRequest extends FormRequest
{
    /**
     * 确定用户是否有权限进行此请求
     */
    public function authorize(): bool
    {
        return true;
    }

    /**
     * 为Scribe文档生成提供查询参数信息
     */
    public function queryParameters(): array
    {
        return [
            'post_type' => [
                'description' => '文章类型，默认为post',
                'example' => 'post',
            ],
            'post_status' => [
                'description' => '文章状态',
                'example' => 'publish',
            ],
            'limit' => [
                'description' => '每页数量，范围1-100，默认10',
                'example' => 10,
            ],
            'page' => [
                'description' => '页码，从1开始，默认1',
                'example' => 1,
            ],
            'orderby' => [
                'description' => '排序字段',
                'example' => 'date',
            ],
            'order' => [
                'description' => '排序方式，ASC或DESC，默认DESC',
                'example' => 'DESC',
            ],
            'ids' => [
                'description' => '包含的文章ID，多个用逗号分隔',
                'example' => '1,2,3',
            ],
            'not_ids' => [
                'description' => '排除的文章ID，多个用逗号分隔',
                'example' => '4,5,6',
            ],
            'cat' => [
                'description' => '分类ID',
                'example' => 1,
            ],
            'cat_ids' => [
                'description' => '包含的分类ID，多个用逗号分隔',
                'example' => '1,2,3',
            ],
            'not_cat_ids' => [
                'description' => '排除的分类ID，多个用逗号分隔',
                'example' => '4,5,6',
            ],
            'tag' => [
                'description' => '标签ID',
                'example' => 1,
            ],
            'tag_ids' => [
                'description' => '包含的标签ID，多个用逗号分隔',
                'example' => '1,2,3',
            ],
            'not_tag_ids' => [
                'description' => '排除的标签ID，多个用逗号分隔',
                'example' => '4,5,6',
            ],
            'author' => [
                'description' => '作者ID',
                'example' => 1,
            ],
            'date' => [
                'description' => '精确日期，格式YYYY-MM-DD',
                'example' => '2024-03-15',
            ],
            'date_from' => [
                'description' => '开始日期，格式YYYY-MM-DD',
                'example' => '2024-03-01',
            ],
            'date_to' => [
                'description' => '结束日期，格式YYYY-MM-DD',
                'example' => '2024-03-31',
            ],
            's' => [
                'description' => '搜索关键词，最多200字符',
                'example' => 'WordPress',
            ],
            'ignore_sticky_posts' => [
                'description' => '是否忽略粘性文章，默认false',
                'example' => false,
            ],
            'sticky_only' => [
                'description' => '是否只返回粘性文章，1或0',
                'example' => '0',
            ],
        ];
    }

    /**
     * 获取应用于请求的验证规则
     */
    public function rules(): array
    {
        return [
            'post_type' => 'sometimes|string|max:20',
            'post_status' => 'sometimes|string|in:publish,private,draft,pending,future,trash,inherit',
            'limit' => 'sometimes|integer|min:1|max:100',
            'page' => 'sometimes|integer|min:1',
            'orderby' => 'sometimes|string|in:date,title,menu_order,rand,ID,author,name,modified,comment_count',
            'order' => 'sometimes|string|in:ASC,DESC',

            // 文章ID相关
            'ids' => 'sometimes|string',
            'not_ids' => 'sometimes|string',

            // 分类相关
            'cat' => 'sometimes|integer',
            'cat_ids' => 'sometimes|string',
            'not_cat_ids' => 'sometimes|string',

            // 标签相关
            'tag' => 'sometimes|integer',
            'tag_ids' => 'sometimes|string',
            'not_tag_ids' => 'sometimes|string',

            // 作者相关
            'author' => 'sometimes|integer',

            // 日期相关
            'date' => 'sometimes|date_format:Y-m-d',
            'date_from' => 'sometimes|date_format:Y-m-d',
            'date_to' => 'sometimes|date_format:Y-m-d|after_or_equal:date_from',

            // 搜索相关
            's' => 'sometimes|string|max:200',

            // 其他参数
            'ignore_sticky_posts' => 'sometimes|boolean',
            'sticky_only' => 'sometimes|in:0,1',
        ];
    }

    /**
     * 获取验证错误的自定义消息
     */
    public function messages(): array
    {
        return [
            'post_status.in' => '文章状态必须是有效的WordPress文章状态',
            'limit.integer' => '每页数量必须是整数',
            'limit.min' => '每页数量最少为1',
            'limit.max' => '每页数量最多为100',
            'page.integer' => '页码必须是整数',
            'page.min' => '页码最少为1',
            'orderby.in' => '排序字段必须是有效的字段名',
            'order.in' => '排序方式必须是ASC或DESC',
            's.max' => '搜索关键词长度不能超过200个字符',
            'tag.integer' => '标签ID必须是整数',
            'author.integer' => '作者ID必须是整数',

            // 日期格式错误消息
            'date.date_format' => '日期格式必须为 YYYY-MM-DD，如：2024-03-15',
            'date_from.date_format' => '开始日期格式必须为 YYYY-MM-DD，如：2024-03-01',
            'date_to.date_format' => '结束日期格式必须为 YYYY-MM-DD，如：2024-03-31',
            'date_to.after_or_equal' => '结束日期不能早于开始日期',
        ];
    }

    /**
     * 处理验证失败的情况
     */
    protected function failedValidation(Validator $validator)
    {
        $errors = $validator->errors()->toArray();
        $message = '请求参数验证失败';

        // 获取第一个错误信息
        if (!empty($errors)) {
            $firstError = array_values($errors)[0];
            $message = is_array($firstError) ? $firstError[0] : $firstError;
        }

        throw new HttpResponseException(
            ApiResponse::error($message, 422, 422, ['validation_errors' => $errors])
        );
    }

    /**
     * 获取经过验证和清理的查询参数
     */
    public function getValidatedQueryParams(): array
    {
        $validated = $this->validated();

        // 处理逗号分隔的ID列表
        $arrayFields = ['ids', 'not_ids', 'cat_ids', 'not_cat_ids', 'tag_ids', 'not_tag_ids'];

        foreach ($arrayFields as $field) {
            if (isset($validated[$field])) {
                $validated[$field] = array_filter(
                    array_map('intval', explode(',', $validated[$field]))
                );
            }
        }

        // 处理布尔值
        if (isset($validated['ignore_sticky_posts'])) {
            $validated['ignore_sticky_posts'] = (bool) $validated['ignore_sticky_posts'];
        }

        return $validated;
    }
}
